$(document).ready(function(){
    var t="",
    e="VND",
    c="xml_jquery_store_"+window.location.hostname,
    n=new Array(),
    a=new Array(),
    o="",
    i="",
    B=new Number(0);
    
    $(".btn_add_cart").live("click",addToCart);
    
    var g=$.cookie(c);
    if(g!=null){
        a = $.parseJSON(g);
    }
    C();
    function addToCart(){
        var productId = $(this).attr('productId');
        var productName = $(this).attr('productName');
        var productPrice = $(this).attr('productPrice');
        var productPromotion = $(this).attr('productPromotion');
        var F = 1;
        alert('Sản phẩm được thêm vào giỏ hàng');
        for(var L in a){
            if(productName == a[L].productName){
                F=a[L].productQty++;
                C();
                return false
            }
        }
        a.push({
            productId:productId,
            productName:productName,
            productPrice:productPrice,
            productPromotion:productPromotion,
            productQty:1
        });
        C();
        z=false;
        return false
    }
    function C(){
        o="";
        i="";
        B=0;
        var E=0;
        for(var F in a){
            var G = a[F];
            // console.log('G.productPrice:'+G.productPrice);
            // console.log('G.productQty:'+G.productQty);
            B=B+((1-G.productPromotion/100)*G.productPrice*G.productQty);
            o+='<tr id="cart_row_'+F+'" style="height:20px;">';
            o+="<td>"+G.productId+"</td>";
            o+="<td>"+G.productName+"</td>";
            o+="<td>"+addCommas(G.productPrice,'.')+"</td>";
            o+='<td><input type="number" step="1" min="1" value="'+G.productQty+'" class="input-small span1 cart_product_qty" style="height:12px;width:50px;"/></td>';
            o+="<td>"+G.productPromotion+" %</td>";
            o+="<td>"+addCommas( ((1-G.productPromotion/100)*G.productPrice*G.productQty),'.')+"</td>";
            o+='<td><a href="#" id="delete_prod_id'+F+'" class="close delete_product_from_cart" title="Delete">&times;</a></td>';
            o+="</tr>";
            E+=G.productQty
        }
        $.cookie(c,$.toJSON(a),{
            path: '/'
        });
        $("#shopping_cart_data").html(o);
        i+="Tổng tiền: <strong>"+addCommas(B,'.') +" "+e+"</strong>";
        $("#shopping_cart_total").html(i);
        $("#show_cartBtn").html(E+'</strong> sản phẩm  trong <i class="icon-shopping-cart"></i><strong>');
        if(B<=0){
            $("#checkout_submit_order").addClass("disabled")
        }else{
            $("#checkout_submit_order").removeClass("disabled")
        }
        return false
    }
    
    $(".delete_product_from_cart").live("click",deleteCart);
    $(".cart_product_qty").live("change",changeProductQuality);
    
    function deleteCart(){
        var F=$(this).attr("id");
        var E=F.substring(14);
        //$("#btn_"+a[E].uProductID).html('Add to <i class="icon-shopping-cart icon-white"></i>');
        a.splice(E,1);
        C();
        return false
    }
    function changeProductQuality(){
        var E=$(this).parent().parent().attr("id"),
        F=E.substring(9);
        if($(this).val()<=0||!Number($(this).val())){
            $(this).val(1)
        }
        a[F].productQty=Math.round($(this).val());
        C();
        return false
    }
    
    /*$("#checkout_submit_order").live("click",function(){
        if(B<=0){
            return false
        }
        $("#cart_holder").modal("hide");
        
    });*/
    
    // get check out info and send mail
    
    $("#btn_purchase").live("click",function(){
        if(a == null || a.Length <= 0){
            alert('Không có sản phẩm nào trong giỏ hàng');
            return false;
        }
        //get data from form checkout-form
        var userId = 0,
        email = '', 
        name = '',
        address = '',
        phone = '';
        $('#checkout-form').find('input').each(function(i, field) {
            if(field.name =='User[id]'){
                userId = field.value;
            }
            if(field.name =='User[email]'){
                email = field.value;
            }
            if(field.name =='User[name]'){
                name = field.value;
            }
            if(field.name =='User[address]'){
                address = field.value;
            }
            if(field.name =='User[phone]'){
                phone = field.value;
            }
        });

        // get data from cookie
        var formdata = new FormData();
        formdata.append("userId", userId);
        formdata.append("email", email);
        formdata.append("name", name);
        formdata.append("address", address);
        formdata.append("phone", phone);
        formdata.append("cartLength", a.length);
        for (i = 0; i < a.length; i++) {
            formdata.append("productId"+i,a[i]['productId']);
            formdata.append("productName"+i,a[i]['productName']);
            formdata.append("productPrice"+i,a[i]['productPrice']);
            formdata.append("productPromotion"+i,a[i]['productPromotion']);
            formdata.append("productQty"+i,a[i]['productQty']);
        }
        
        // ajax
        $.ajax({
            url: "checkout",
            type: "POST",
            data: formdata,
            timeout:120000,
            dataType: 'json',
            processData: false,
            contentType: false,
            beforeSend:function(){
                $('#checkout_result').html('<img width="64" height="42" src="../css/img/ajax-loader.gif" />');                    
            },
            error: function(a,b,c) {
            // alert('error:'+c);
            },
            success: function(response){
                // alert('sucess');
                $("#checkout_result").html(response.message); 
                $("#checkout_f").html(response.output_html);                
            },
            complete: function(){
                // alert('delete '+c);
                /*$.cookie(c, '', {
                    path: '/'
                });*/
                $.removeCookie(c, {
                    path: '/'
                });
                $("#show_cartBtn").html('0</strong> sản phẩm  trong <i class="icon-shopping-cart"></i><strong>');
            
            }
        });
        
    });
    
    function addCommas(nStr,symbol) {
        nStr += '';
        var x = nStr.split('.');
        var x1 = x[0];   
        var rgx = /(\d+)(\d{3})/;
        while (rgx.test(x1)) {
            x1 = x1.replace(rgx, '$1' + symbol + '$2');
        }
        return x1;
    }
});

